<?php
namespace Modules\Category\Http\Controllers\Erp\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Category\Entities\Category;

use Validator;
use ThrowException;
use DB;

class CategoryController extends Controller
{
    public function store(Request $req)
    {
        $rule = [
            'list'  => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $list = $req->input('list');

        // 导入模式为2时为全量覆盖导入
        if ($req->input('mode') == 2) {
            Category::where('id', '>', 0)->type('normal')->forceDelete();
        }

        DB::beginTransaction();

        foreach ($list as $item) {
            $id = @$item['id'] ?: ThrowException::Conflict('缺少分类id');

            Category::where('id',  $id)->forceDelete();

            $item['type'] = 'normal';
            Category::create($item);
        }

        DB::commit();

        return [
        ];
    }

}
